#coding=utf-8
import cv2
import numpy as np
import matplotlib as plt

def mo(img,kernel):
  
    #erode
    eroded = cv2.erode(img,kernel)
     
    #dilate
    dilated = cv2.dilate(img,kernel)
     
    #open
    opened=cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
     
    #close
    closed=cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
    


    return eroded,dilated,opened,closed


def ex(img,kernel):
    
        #gradient
        gradient=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
        
        #tophat
        tophat=cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
    
        #balckhat
        balckhat=cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
        return gradient,tophat,balckhat



if __name__ == '__main__':
    img = cv2.imread('..\\img\\morph.bmp',0)
    
    #OpenCV structure element
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))

    eroded,dilated,opened,closed=mo(img,kernel)
    gradient,tophat,balckhat=ex(img,kernel)
    #show
    cv2.imshow("Origin", img)
    cv2.imshow("Eroded ",eroded);
    cv2.imshow("Dilated ",dilated);
    cv2.imshow("Opened ",opened);
    cv2.imshow("Closed ",closed);
    cv2.imshow("gradient ",gradient);
    cv2.imshow("tophat ",tophat);
    cv2.imshow("balckhat ",balckhat);
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()


